package com.aitaoxue.palx.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.http.Header;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.api.ApiHttpClient;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseFragment;
import com.aitaoxue.palx.bean.BannerUrl;
import com.aitaoxue.palx.bean.Base;
import com.aitaoxue.palx.bean.Url;
import com.aitaoxue.palx.bean.UserStatus;
import com.aitaoxue.palx.ui.CityChooseAvtivity;
import com.aitaoxue.palx.ui.EQBookListActivity;
import com.aitaoxue.palx.ui.MoneyAndPointActivity;
import com.aitaoxue.palx.ui.PersonCenterActivity;
import com.aitaoxue.palx.ui.PullOrderActivity;
import com.aitaoxue.palx.ui.SearchActivity;
import com.aitaoxue.palx.ui.register.GuideActivity;
import com.aitaoxue.palx.util.GsonUtil;
import com.aitaoxue.palx.util.TLog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.viewpagerindicator.CirclePageIndicator;

public class MainFragment extends BaseFragment {
	private static final String TAG = MainFragment.class.getSimpleName();

	private static final int CHOOSE_CITY_STATUS = 1;

	// 首页banners数目
	private static final int IMAGE_NUM = 4;

	@InjectView(R.id.home_fragment_city_tv)
	public TextView tv_city;

	@InjectView(R.id.home_fragment_city_iv)
	public ImageView iv_city;

	@InjectView(R.id.home_fragment_viewpager)
	public ViewPager viewPager;

	@InjectView(R.id.indicator)
	public CirclePageIndicator indicator;

	@InjectView(R.id.home_fragment_alert)
	public RelativeLayout alert;

	@InjectView(R.id.home_fragment_message)
	public TextView alertMessage;

	@InjectView(R.id.home_fragment_search)
	public ImageView searchButton;

	// 查看资金和积分
	@InjectView(R.id.grid_first)
	public RelativeLayout gridFirst;
	@InjectView(R.id.grid_second)
	public RelativeLayout gridSecond;
	@InjectView(R.id.grid_third)
	public RelativeLayout gridThird;
	@InjectView(R.id.grid_fourth)
	public RelativeLayout gridFourth;

	private PagerAdapter mPageAdapter;

	// 当前的banners轮转图片index
	private int currentItem = 0;

	// 保存banners urls
	private List<String> links;

	private List<ScreenSlidePageFragment> fragments;

	private static final int status_not_complete = 0;
	private static final int status_ing = 1;
	private int STATUS;

	// 定时器
	private ScheduledExecutorService scheduledExecutorService;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.home_fragment, null);
		ButterKnife.inject(this, view);
		initView(view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		fragments = new ArrayList<ScreenSlidePageFragment>();
		for (int i = 0; i < IMAGE_NUM; i++) {
			ScreenSlidePageFragment fragment = new ScreenSlidePageFragment(i);
			fragments.add(fragment);
		}

		mPageAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
		viewPager.setAdapter(mPageAdapter);

		indicator.setViewPager(viewPager);
		indicator.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				currentItem = position;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});

		// viewPager.setPageTransformer(true, new DepthPageTransformer());
		initData();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.home_fragment_city_tv:
		case R.id.home_fragment_city_iv:
			startActivityForResult(new Intent(getActivity(),
					CityChooseAvtivity.class), CHOOSE_CITY_STATUS);
			break;
		case R.id.home_fragment_search:
			startActivity(new Intent(getActivity(), SearchActivity.class));
			break;
		case R.id.grid_first:
			startActivity(new Intent(getActivity(), MoneyAndPointActivity.class));
			break;
		case R.id.grid_second:
			Intent intent = new Intent(getActivity(),
					PersonCenterActivity.class);
			intent.putExtra("isMine", true);
			startActivity(intent);
			break;
		case R.id.grid_third:
			Intent intent2 = new Intent(getActivity(), PullOrderActivity.class);
			startActivity(intent2);
			break;
		case R.id.grid_fourth:
			startActivity(new Intent(getActivity(), EQBookListActivity.class));
			break;
		case R.id.home_fragment_alert:
			if (STATUS == status_not_complete) {
				startActivity(new Intent(getActivity(), GuideActivity.class));
			} else {
				AitaoXueApi.getTeacherStatus(mStatusHandler);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void initView(View view) {
		tv_city.setOnClickListener(this);
		iv_city.setOnClickListener(this);
		searchButton.setOnClickListener(this);
		gridFirst.setOnClickListener(this);
		gridSecond.setOnClickListener(this);
		gridThird.setOnClickListener(this);
		gridFourth.setOnClickListener(this);
		alert.setOnClickListener(this);
	}

	@Override
	public void initData() {
		links = new ArrayList<String>();
		getBannersUrls();
		getUserStatus();
		// getAccountNum();

		String city = AppContext.getInstance().getProperty("user.city");
		if (city != null) {
			setCity(city);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CHOOSE_CITY_STATUS
				&& resultCode == getActivity().RESULT_OK) {
			// 获得城市成功
			if (data.getStringExtra("selected_city") != null) {
				setCity(data.getStringExtra("selected_city"));
			}
		}
	}

	private class ScreenSlidePagerAdapter extends FragmentPagerAdapter {

		public ScreenSlidePagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			TLog.log(TAG, "slide:" + position);
			fragments.get(position).changeImg();
			return fragments.get(position);
		}

		@Override
		public int getCount() {
			return IMAGE_NUM;
		}
	}

	@Override
	public void onStart() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		scheduledExecutorService.scheduleAtFixedRate(new ViewPagerTask(), 1, 5,
				TimeUnit.SECONDS);

		super.onStart();
	}

	@Override
	public void onStop() {
		scheduledExecutorService.shutdown();

		super.onStop();
	}

	private class ViewPagerTask implements Runnable {

		@Override
		public void run() {
			currentItem = (currentItem + 1) % IMAGE_NUM;
			handler.obtainMessage().sendToTarget();
		}

	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			viewPager.setCurrentItem(currentItem);
		}
	};

	private void getBannersUrls() {
		AitaoXueApi.getBannersUrls(mHandler);
	}

	private AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBytes) {
			String result = new String(responseBytes);
			BannerUrl bannerUrl = GsonUtil.GsonToBean(result, BannerUrl.class);
			List<Url> list = bannerUrl.getContent();
			for (Url url : list) {
				String partUrl = url.getUrl();
				links.add(ApiHttpClient.IMG_URL_PREFIX + partUrl);
			}
			// 通知子fragment url获得
			notifyUrlGet();
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}
	};

	private AsyncHttpResponseHandler mStatusHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String result = new String(arg2);
			UserStatus userStatus = GsonUtil.GsonToBean(result,
					UserStatus.class);
			Base base = userStatus.getContent();
			String status = base.getStatus();
			switch (Integer.parseInt(status)) {
			case 0: // 认证信息不完整
				STATUS = status_not_complete;
				alertMessage.setText("您的信息不完整,请点击完善");
				alert.setVisibility(View.VISIBLE);
				alert.setClickable(true);
				break;
			case 1: // 认证通过
				break;
			case 2: // 认证中
				STATUS = status_ing;
				alertMessage.setText("您的信息正在认证中,请点击刷新");
				alert.setVisibility(View.VISIBLE);
				alert.setClickable(true);
				break;
			default:
				break;
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			// TODO Auto-generated method stub

		}
	};

	private void notifyUrlGet() {
		TLog.log(TAG, fragments.size() + "");
		for (ScreenSlidePageFragment fragment : fragments) {
			fragment.setUrl(links.get(fragment.getIndex()));
			fragment.changeImg();
			TLog.log(TAG,
					fragment.getIndex() + ":" + links.get(fragment.getIndex()));
		}
	}

	public void setCity(String city) {
		int index = city.indexOf("市");
		String showCity = city
				.substring(0, index == -1 ? city.length() : index);
		tv_city.setText(showCity);
	}

	// private void getAccountNum() {
	// AitaoXueApi.getTeacherMoney(moneyHandler);
	// }

	private void getUserStatus() {
		AitaoXueApi.getTeacherStatus(mStatusHandler);
	}

}
